package com.igroupes.ovineherd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.igroupes.ovineherd.dto.request.DataOriginKeyAddRequest;
import com.igroupes.ovineherd.dto.request.DataOriginKeyRequest;
import com.igroupes.ovineherd.dto.request.DataOriginUpdateRequest;
import com.igroupes.ovineherd.dto.response.DataOriginGetResponse;
import com.igroupes.ovineherd.entity.DataOriginEntity;
import com.igroupes.ovineherd.raw.service.DataOriginService;
import com.igroupes.ovineherd.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("fontstored")
public class OriginalController {
    @Autowired
    private DataOriginService dataOriginService;

    @PostMapping("")
    public ResultVO add(@Valid @RequestBody DataOriginKeyAddRequest request) {
        DataOriginEntity dataOriginEntity = new DataOriginEntity();
        BeanUtils.copyProperties(request,dataOriginEntity);
        dataOriginService.save(dataOriginEntity);
        return ResultVO.success();
    }

    @DeleteMapping("/{id}")
    public ResultVO remove(@PathVariable Long id ) {
        QueryWrapper<DataOriginEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DataOriginEntity::getId, id);
        dataOriginService.remove(wrapper);
        return ResultVO.success();
    }

    @GetMapping()
    public ResultVO get(@Valid DataOriginKeyRequest request) {
        QueryWrapper<DataOriginEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DataOriginEntity::getParentKey, request.getParentKey())
                .eq(DataOriginEntity::getKey, request.getKey());
        List<DataOriginGetResponse.DataOriginGetResponseDetail> responseList = dataOriginService.list(wrapper).stream().map(entity -> {
            DataOriginGetResponse.DataOriginGetResponseDetail dataOriginGetResponseDetail = new DataOriginGetResponse.DataOriginGetResponseDetail();
            BeanUtils.copyProperties(entity, dataOriginGetResponseDetail);
            return dataOriginGetResponseDetail;
        }).collect(Collectors.toList());
        DataOriginGetResponse dataOriginGetResponse = new DataOriginGetResponse();
        dataOriginGetResponse.setData(responseList);
        return ResultVO.success(dataOriginGetResponse);
    }

    @PutMapping("/{id}")
    public ResultVO update(@PathVariable Long id , @Valid @RequestBody DataOriginUpdateRequest request) {
        DataOriginEntity dataOriginEntity = new DataOriginEntity();

        BeanUtils.copyProperties(request,dataOriginEntity);
        dataOriginEntity.setId(id);
        dataOriginService.updateById(dataOriginEntity);
        return ResultVO.success();
    }

}
